package com.web;

import com.dao.StudentDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Date;

@WebServlet("/student/add")
public class StuAddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/student/add.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String no = req.getParameter("no");
        String name = req.getParameter("name");
        String age = req.getParameter("age");
        String sex = req.getParameter("sex");
        String score = req.getParameter("score");
        String time = req.getParameter("time");

        if (no == null || name == null || age == null || sex == null || score == null || time == null) {
            req.setAttribute("message", "参数不对");
            req.getRequestDispatcher("/student/message.jsp").forward(req, resp);
            return;
        }
        try {
            new StudentDao().insert(no, name, Integer.parseInt(age), sex, Float.parseFloat(score), Date.valueOf(time));

            req.setAttribute("message", "添加成功");
            req.getRequestDispatcher("/student/message.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("message", "添加失败" + e.getLocalizedMessage());
            req.getRequestDispatcher("/student/message.jsp").forward(req, resp);
        }
    }
}
